package P169;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author DJ同学
 * @Date 2021/2/17 14:54
 * @Version 1.0
 * @Name 多数元素
 * @Problem https://leetcode-cn.com/problems/majority-element/
 * @Idea HashMap
 */
public class Solution {
    public int majorityElement(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i = 0;i<nums.length;i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i])+1);
            }else{
                map.put(nums[i],1);
            }
        }
        Integer res = 0;
        Iterator<Map.Entry<Integer,Integer>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<Integer,Integer> entry = iterator.next();
            if(entry.getValue()>nums.length/2){
                res = entry.getKey();
                break;
            }
        }
        return res;
    }
}
